package com.shiliuzi.www.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

public class OSSClientUtil {
    private static final String END_POINT = "oss-cn-guangzhou.aliyuncs.com";

    private static final String ACCESS_KEY_ID = "LTAI5t6z17ZrattCXHUYZzCH";

    private static final String ACCESS_KEY_SECRET = "wHadRWmFZ1cIXmc2uWSdBPjJFNXkfp";

    private static final String BUCKET_NAME = "shuliuzi-fashion";

    private volatile static OSS instance;

    /**
     * 单例
     * @return OSS工具类实例
     */
    private static OSS getOSSClient() {
        if (instance == null) {
            synchronized (OSSClientUtil.class) {
                if (instance == null) {
                    instance = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
                }
            }
        }
        return instance;
    }

    public static String upload(MultipartFile file) {
        OSS ossClient = getOSSClient();
        try {
            // 构建文件名
            String originName = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString();
            String suffix = originName.substring(originName.lastIndexOf("."));
            String newFileName = fileName + suffix;

            // 文件上传
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, newFileName, file.getInputStream());
            ossClient.putObject(putObjectRequest);
            return newFileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }


    public static String download(String fileName, String pathName) {
        OSS ossClient = getOSSClient();
        try {
            OSSObject ossObject = ossClient.getObject(BUCKET_NAME, fileName);
            InputStream inputStream = ossObject.getObjectContent();
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pathName + "/" + fileName));
            byte[] bys = new byte[1024];
            int len;
            while ((len = inputStream.read(bys)) != -1) {
                outputStream.write(bys, 0, len);
            }
            inputStream.close();
            outputStream.close();
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    public static String generateUrl (String fileName) {
        return "https://" + BUCKET_NAME + "." + END_POINT + "/" + fileName;
    }


}